import React, { useState, useEffect, useRef } from 'react';
import ReactMarkdown from 'react-markdown';
import { Card } from '../../types';
import styles from './Notebook.module.css';

interface CardEditorProps {
  card: Card;
  //onSave设置卡片的保存功能
  onSave: (card: Card) => void;
  // onDeleteCard设置卡片的删除功能
  onDeleteCard: (cardId: string) => void;
}

const CardEditor: React.FC<CardEditorProps> = ({ card, onSave, onDeleteCard }) => {
  const [title, setTitle] = useState(card.title);
  const [content, setContent] = useState(card.content);
  //是否预览
  const [isPreview, setIsPreview] = useState(false);
  // 文本区域引用
  const textareaRef = useRef<HTMLTextAreaElement>(null);
  // 新增的状态
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [refinedContent, setRefinedContent] = useState('');
  // 添加AI润色加载状态
  const [isRefining, setIsRefining] = useState(false);

  //**cardeditor被挂载后渲染标题和内容，切换卡片触发新渲染**// 
  useEffect(() => {
    setTitle(card.title);
    setContent(card.content);
  }, [card]);

  //调用props的onSave方法，保存卡片
  const handleSave = () => {
    onSave({
      ...card,
      title,
      content,
    });
  };

  // 处理格式化操作
  const handleFormat = (formatType: string) => {
    if (isPreview || !textareaRef.current) return;
    
    const textarea = textareaRef.current;
    const start = textarea.selectionStart;
    const end = textarea.selectionEnd;
    const selectedText = content.substring(start, end);
    
    if (start === end) return; // 没有选中文本
    
    let formattedText = '';
    let cursorPosition = 0;
    
    switch (formatType) {
      case 'bold':
        formattedText = `**${selectedText}**`;
        cursorPosition = end + 4;
        break;
      case 'italic':
        formattedText = `*${selectedText}*`;
        cursorPosition = end + 2;
        break;
      case 'unordered-list':
        formattedText = selectedText
          .split('\n')
          .map(line => `- ${line}`)
          .join('\n');
        cursorPosition = end + selectedText.split('\n').length * 2;
        break;
      case 'ordered-list':
        formattedText = selectedText
          .split('\n')
          .map((line, index) => `${index + 1}. ${line}`)
          .join('\n');
        cursorPosition = end + selectedText.split('\n').length * 3;
        break;
      case 'code':
        // 添加语言选择，默认为javascript
        const language = window.prompt('输入代码语言 (如javascript, python, css等):', 'javascript') || 'javascript';
        formattedText = `\`\`\`${language}\n${selectedText}\n\`\`\``;
        cursorPosition = end + 8 + language.length;
        break;
      case 'link':
        formattedText = `[${selectedText}](${selectedText})`;
        cursorPosition = end + selectedText.length + 4;
        break;
      case 'quote':
        formattedText = selectedText
          .split('\n')
          .map(line => `> ${line}`)
          .join('\n');
        cursorPosition = end + selectedText.split('\n').length * 2;
        break;
      default:
        return;
    }
    
    const newContent = content.substring(0, start) + formattedText + content.substring(end);
    setContent(newContent);
    
    // 设置光标位置
    setTimeout(() => {
      textarea.focus();
      textarea.setSelectionRange(cursorPosition, cursorPosition);
    }, 0);
  };

  //从剪贴板中获取图像文件，上传到图床，并将返回的图像URL以markdown形式插入到文本区域中
  const handlePaste = async (e: React.ClipboardEvent<HTMLTextAreaElement>) => {
    const items = e.clipboardData.items;
    console.log('剪贴板 items:', items);

    for (let i = 0; i < items.length; i++) {
      const item = items[i];
      console.log(`第${i}个item:`, item, 'type:', item.type);

      if (item.type.indexOf('image') !== -1) {
        //阻止浏览器的默认粘贴行为，自行处理图像的粘贴事务
        e.preventDefault();
        const file = item.getAsFile();
        console.log('获取到的 file:', file);

        if (file) {
          try {
            // const formData = new FormData();
            // formData.append('file', file);

            // const response = await fetch('https://corsproxy.io/?https://111.230.111.196:8080/upload', {
            //   method: 'POST',
            //   headers: {
            //     Authorization: 'Bearer 1|1uRrzuZqGPmalOXM6NV1zg8e429lZqGYY5ItO3ff',
            //     Accept: 'application/json'
            //   },
            //   body: formData
            // });
            // const result = await response.json();
            // console.log('上传返回 result:', result);

            const formData = new FormData();
            formData.append('file', file);
            
            const response = await fetch('http://localhost:3001/proxy-upload', {
              method: 'POST',
              body: formData
            });
            const result = await response.json();
            console.log(result);

            const imageUrl = result.data?.url || result.url || result.data?.links?.url;
            console.log('图片url:', imageUrl);

            if (imageUrl) {
              // 插入markdown图片语法
              const textarea = textareaRef.current;
              if (textarea) {
                const start = textarea.selectionStart;
                const end = textarea.selectionEnd;
                const before = content.substring(0, start);
                const after = content.substring(end);
                const markdownImage = `![image](${imageUrl})`;
                const newContent = before + markdownImage + after;
                setContent(newContent);
                setTimeout(() => {
                  textarea.focus();
                  textarea.setSelectionRange(before.length + markdownImage.length, before.length + markdownImage.length);
                }, 0);
              }
            } else {
              alert('图片上传成功，但未获取到图片URL');
            }
          } catch (err) {
            console.error('图片上传异常:', err);
            alert('图片上传失败（异常）');
          }
        } else {
          alert('未能从剪贴板获取到图片文件');
        }
        break; // 只处理第一个图片
      }
    }
  };

  const handleDelete = () => {
    onDeleteCard(card.id);
  };

  // 处理AI完善功能
  const handleAIRefine = async () => {
    if (isRefining) return; // 防止重复点击
    
    try {
      setIsRefining(true); // 设置加载状态为true
      
      const response = await fetch('http://localhost:5000/api/refine', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          messages: [
            { 
              role: 'system', 
              content: '你是一名专业的文字润色助手，请根据用户提供的笔记内容，在保持原意和核心信息的前提下进行优化。要求：1. 语言风格：保持用户原有风格;2. 结构调整：优化逻辑衔接，使段落过渡自然;3. 语法修正：纠正明显的语法/拼写错误\n4. 表达优化：替换重复/模糊表述，提升准确性\n5. 输出格式：保留原有markdown排版结构（列表/标题层级等）请开始优化。' 
            },
            { role: 'user', content: content }
          ]
        }),
      });
      const data = await response.json();
      setRefinedContent(data.result); // 设置润色后的内容
      setIsModalOpen(true); // 打开模态框
    } catch (error) {
      console.error('请求失败:', error);
      alert('AI润色请求失败，请稍后重试');
    } finally {
      setIsRefining(false); // 无论成功或失败都设置加载状态为false
    }
  };

  // 接受润色后的内容
  const acceptRefinement = () => {
    setContent(refinedContent); // 更新内容区域为润色后的内容
    setIsModalOpen(false); // 关闭模态框
    
    // 自动保存润色后的卡片内容
    onSave({
      ...card,
      title,
      content: refinedContent,
    });
  };

  // 拒绝润色后的内容
  const rejectRefinement = () => {
    setIsModalOpen(false); // 关闭模态框，不做任何修改
  };

  return (
    <div className={styles.cardEditor}>
      <div className={styles.editorHeader}>
        <div className={styles.editorHeaderLeft}>
          <input
            type="text"
            className={styles.cardTitleInput}
            value={title}
            onChange={(e) => setTitle(e.target.value)}
          />
          {isRefining && (
            <div className={styles.refiningIndicator}>
              <i className="bi bi-hourglass-split"></i> AI润色中，请耐心等待...
            </div>
          )}
        </div>
        <div className={styles.editorActions}>
          <button className={styles.btnOutline} onClick={handleAIRefine} disabled={isRefining}>
            <i className={`bi ${isRefining ? 'bi-hourglass' : 'bi-magic'}`}></i> {isRefining ? '润色中...' : 'AI完善'}
          </button>
          <button className={styles.btnOutline} onClick={handleDelete}>
            <i className="bi bi-trash"></i> 删除
          </button>
          <button className={styles.btnPrimary} onClick={handleSave}>
            <i className="bi bi-check-lg"></i> 保存
          </button>
        </div>
      </div>
      
      {/* 模态框部分保持不变 */}
      {isModalOpen && (
        <div className={styles.modal}>
          <div className={styles.modalContent}>
            <h2>润色后的内容</h2>
            <ReactMarkdown>{refinedContent}</ReactMarkdown>
            <div className={styles.modalButtons}>
              <button className={styles.btnAccept} onClick={acceptRefinement}>
                <i className="bi bi-check-circle"></i> 接受
              </button>
              <button className={styles.btnReject} onClick={rejectRefinement}>
                <i className="bi bi-x-circle"></i> 拒绝
              </button>
              <button className={styles.btnClose} onClick={() => setIsModalOpen(false)}>
                <i className="bi bi-x"></i> 关闭
              </button>
            </div>
          </div>
        </div>
      )}
      
      {/* 其余部分保持不变 */}
      <div className={styles.editorToolbar}>
        <button onClick={() => setIsPreview(!isPreview)}>
          {/* eye切换预览以及pencil切换编辑模式 */}
          <i className={`bi bi-${isPreview ? 'pencil' : 'eye'}`}></i>
        </button>
        {/* 字体加粗、斜体、无序列表、有序列表、代码、链接、引用等 ，图片需要另外处理*/}
        <button onClick={() => handleFormat('bold')} disabled={isPreview}>
          <i className="bi bi-type-bold"></i>
        </button>
        <button onClick={() => handleFormat('italic')} disabled={isPreview}>
          <i className="bi bi-type-italic"></i>
        </button>
        <button onClick={() => handleFormat('unordered-list')} disabled={isPreview}>
          <i className="bi bi-list-ul"></i>
        </button>
        <button onClick={() => handleFormat('ordered-list')} disabled={isPreview}>
          <i className="bi bi-list-ol"></i>
        </button>
        <button onClick={() => handleFormat('code')} disabled={isPreview}>
          <i className="bi bi-code-slash"></i>
        </button>
        <button onClick={() => handleFormat('link')} disabled={isPreview}>
          <i className="bi bi-link"></i>
        </button>
        <button><i className="bi bi-image"></i></button>
        <button onClick={() => handleFormat('quote')} disabled={isPreview}>
          <i className="bi bi-blockquote-left"></i>
        </button>
      </div>
      <div className={styles.editorContent}>
        {isPreview ? (
          <div className={styles.preview}>
            <ReactMarkdown>{content}</ReactMarkdown>
          </div>
        ) : (
          <textarea
            ref={textareaRef}
            value={content}
            onChange={(e) => setContent(e.target.value)}
            onPaste={handlePaste}
            placeholder="在此输入卡片内容..."
          />
        )}
      </div>
      <div className={styles.editorFooter}>
        <span>
          <i className="bi bi-clock"></i> 编辑完成，请及时保存，以免数据丢失！
        </span>
      </div>
    </div>
  );
};

export default CardEditor; 